package com.physics.mps.module.abaqus;

import com.physics.mps.common.util.AssertUtil;
import com.physics.mps.entity.enums.CodeEnum;
import com.physics.mps.entity.vo.OpenAbaqusFileVo;
import com.physics.mps.entity.vo.ResponseResult;
import com.physics.mps.module.base.AppConfig;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.io.*;

/**
 * @author mcsoft
 * @since 2023/8/22
 */
@Component
@RequiredArgsConstructor
public class AbaqusHandler {


    // ~ Variable & Constant
    // ========================================================================================================


    // ~ Public method
    // ========================================================================================================

    public static void main(String[] args) {

    }

    public ResponseResult openAbaqusFile(OpenAbaqusFileVo openAbaqusFileVo) throws IOException, InterruptedException {

        String filePath = openAbaqusFileVo.getFilePath();
        String fileName = openAbaqusFileVo.getFileName();

        String openAbaqusFileCommand = createOpenAbaqusFileCommand(filePath, fileName);

        ProcessBuilder processBuilder = new ProcessBuilder("cmd.exe", "/c", openAbaqusFileCommand);

        // 启动进程
        Process process = processBuilder.start();

        // 获取命令输出流
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line;
        StringBuilder output = new StringBuilder();

        // 读取命令输出
        while ((line = reader.readLine()) != null) {
            output.append(line).append("\n");
        }

        // 等待命令执行完毕并获取返回值
        int exitValue = process.waitFor();

        // 打印输出结果和返回值
        ResponseResult success = ResponseResult.success(output.toString());
        return success;

    }

    // ~ Override method
    // ========================================================================================================


    // ~ Private method
    // ========================================================================================================

    private String createOpenAbaqusFileCommand(String filePath, String fileName) {

        AssertUtil.isBlank(filePath, CodeEnum.FILE_NAME_NULL);
        AssertUtil.isBlank(fileName, CodeEnum.FILE_PATH_NULL);

        StringBuilder builder = new StringBuilder();
        builder
                .append(" cd ")
                .append(filePath)
                .append(" && ")
                .append(" abaqus cae noGUI=")
                .append(fileName)
        ;
        return builder.toString();
    }

    // ~ Autowired
    // ========================================================================================================

    private final AppConfig appConfig;

}
